package com.pdf.generate_pdf.common;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.font.FontProgram;
import com.itextpdf.io.font.FontProgramFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.font.FontProvider;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * PDF工具类
 *
 * @author zzt
 * @date 2021/12/8
 */
@Component
@Slf4j
public class PdfUtil {

    private static Configuration configuration;

    static {

    }

    /**
     * 生成pdf工具
     * @param bytes:模板
     * @param obj:数据
     * @param outPutPath:输出路径
     */
    public static void generatePdfByByteArrays(byte[] bytes, Object obj, String outPutPath) {
        File file = new File(outPutPath);
        try (OutputStream fos = new FileOutputStream(file);
             PdfWriter pdfWriter = new PdfWriter(fos);
             PdfDocument pdfDocument = new PdfDocument(pdfWriter);
             StringWriter templateOut = new StringWriter();
             InputStreamReader inputStreamReader = new InputStreamReader(new ByteArrayInputStream(bytes), StandardCharsets.UTF_8)) {
            if (ObjectUtils.isEmpty(configuration)) {
                synchronized (PdfUtil.class) {
                    if (ObjectUtils.isEmpty(configuration)) {
                        configuration = new Configuration(Configuration.VERSION_2_3_28);
                        configuration.setTemplateLoader(new StringTemplateLoader());
                        configuration.setDefaultEncoding("UTF-8");
                    }
                }
            }

            Template template = new Template("template", inputStreamReader, configuration);
            template.process(obj, templateOut);
            String html = templateOut.toString();
            if (StringUtils.isEmpty(html)) {
                log.error("模板存在错误!");
            }
            HtmlConverter.convertToPdf(html, pdfDocument, buildConvertProperties());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 构建字体
     *
     * @return
     */
    private static ConverterProperties buildConvertProperties() {
        try {
            ConverterProperties converterProperties = new ConverterProperties();
            File fontsDirectory = getClassPathStaticFile("static/fonts");
            File[] fontFiles = fontsDirectory.listFiles();
            FontProvider fontProvider = new FontProvider();
            for (File file : fontFiles) {
                FontProgram fontProgram = FontProgramFactory.createFont(file.getAbsolutePath(), true);
                fontProvider.addFont(fontProgram);
            }
            converterProperties.setFontProvider(fontProvider);
            converterProperties.setBaseUri(getClassPathStaticFile("static").getAbsolutePath());
            return converterProperties;
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * 获取字体
     *
     * @param classPath
     * @return
     */
    public static File getClassPathStaticFile(String classPath) {
        try {
            File file = null;
            if (StringUtils.isEmpty(classPath)) {
                file = new File(ResourceUtils.getURL("classpath:").getPath());
            } else {
                file = new File(ResourceUtils.getURL("classpath:" + classPath).getPath());
            }

            return file;
        } catch (Exception e) {
            log.error("获取路径错误：" + classPath, e);
            return null;
        }
    }
}
